const express = require("express");
const axios = require("axios");
const { v4: uuidv4 } = require('uuid');

const app = express();
app.use(express.static("."))
app.use(express.json());


const SILICONFLOW_API_KEY = "sk-mjcghvuxhgettbzopobxxgabjdqanniqvmdyavgormvchjwu"; 
const SILICONFLOW_API_URL = "https://api.siliconflow.cn/v1/chat/completions";

// 存储用户会话的对象，键为会话ID，值为消息历史
const sessions = {};

// 定义 /chat 接口
app.post("/chat", async (req, res) => {
    try {
        const { message } = req.body;
        let { sessionId } = req.body;
        
        // 调试日志：打印接收到的请求数据
        console.log('收到请求 - sessionId:', sessionId, 'message:', message);
        
        // 如果前端没有提供sessionId，生成新的sessionId
        if (!sessionId) {
            sessionId = uuidv4();
            res.setHeader('X-Session-Id', sessionId);
        }
        
        // 如果会话ID不存在，则创建新会话
        if (!sessions[sessionId]) {
            sessions[sessionId] = [];
        }
        
        // 将用户消息添加到历史记录
        sessions[sessionId].push({
            role: "user",
            content: message
        });
        console.log('message',sessions[sessionId])
        const response = await axios.post(
            SILICONFLOW_API_URL,
            {
                model: "Qwen/Qwen3-235B-A22B",
                messages: sessions[sessionId],
                max_tokens: 512,
                temperature: 0.7,
            },
            {
                headers: {
                    "Authorization": `Bearer ${SILICONFLOW_API_KEY}`,
                    "Content-Type": "application/json",
                },
            }
        );

        const aiReply = response.data.choices[0].message.content;
        
        // 调试日志：打印AI回复和当前会话历史
        console.log('AI回复:', aiReply);
        console.log('当前会话历史:', sessions[sessionId]);
        
        // 将AI回复添加到历史记录
        sessions[sessionId].push({
            role: "assistant",
            content: aiReply
        });
        
        // 返回AI的回复和当前会话历史
        res.json({ 
            reply: aiReply,
            history: sessions[sessionId]
        });
    } catch (error) {
        console.error("API调用失败:", error.message);
        res.status(500).json({ error: "AI服务调用失败" });
    }
});

// 清除会话历史的接口
app.post("/clear-chat", (req, res) => {
    const { sessionId } = req.body;
    if (sessions[sessionId]) {
        // 只保留系统消息
        sessions[sessionId] = [
        ];
        res.json({ success: true, message: "会话已清除" });
    } else {
        res.status(404).json({ success: false, message: "会话不存在" });
    }
});

// 启动服务器
const PORT = 3001;
app.listen(PORT, () => {
    console.log(`服务器启动成功，端口: ${PORT}`);
});